<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>4-getSnapShotBeforUpdate的使用场景</title>
    <style>
        .list{
            width: 200px;
            height: 150px;
            background-color: skyblue;
            overflow: auto;
        }
        .news{
            height: 30px;
        }
    </style>
</head>
<body>
<!--准备好一个容器-->
<div id="root"></div>

<!--引入React核心库-->
<script type="text/javascript" src="../0-ReactJs-v17.0.2/react.development.js"></script>
<!--引入React-Dom，用于支持React操作Dom-->
<script type="text/javascript" src="../0-ReactJs-v17.0.2/react-dom.development.js"></script>
<!--引入babel，用于将jsx转为js-->
<script type="text/javascript" src="../0-ReactJs-v17.0.2/babel.min.js"></script>

<script type="text/babel">

    class NewList extends React.Component{

        state = {
            newsArr:[]
        }

        componentDidMount(){
            setInterval(()=>{
                //获取原状态
                const {newsArr} = this.state

                //模拟一条新闻
                const news = '新闻'+(newsArr.length +1)

                //更新状态
                this.setState({
                    newsArr: [news,...newsArr]
                })
            },1000)
        }

        getSnapshotBeforeUpdate(){
            return this.refs.list.scrollHeight;
        }

        componentDidUpdate(preProps,preState,height){
            this.refs.list.scrollTop += this.refs.list.scrollHeight - height
        }

        render(){
            return (
                <div className="list" ref="list">
                    {this.state.newsArr.map((n,index)=>{
                        return <div className="news" key={index}>{n}</div>
                    })}
                </div>
            )
        }
    }

    //渲染组件到页面
    ReactDOM.render(<NewList/>, document.getElementById('root'));
    // ReactDOM.render(<A/>, document.getElementById('root2'));
</script>

</body>
</html>
